package com.licode.codekit.utils;

import com.intellij.util.ResourceUtil;
import com.licode.codekit.buildprj.CodeKitConf;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class DbDriverDlUtil {
    public static boolean downMysqlFromResource(String savePath, boolean fromNet) {
        if (!doDownMysqlFromResource(savePath)) {
            return fromNet && downMysql8019Driver(savePath);
        } else {
            return true;
        }
    }

    private static boolean doDownMysqlFromResource(String savePath) {
        boolean done = false;
        String driverJar = "mysql-driver.jar";
        InputStream inputStream = null;

        if (!checkSavePath(savePath)) {
            return false;
        }

        try {
            inputStream = FileUtil.getRootResourceAsStream(driverJar);
            saveDriveFile(inputStream, savePath);
            done = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignore) {
                }
            }
        }

        return done;
    }
    public static boolean downMysql8019Driver(String savePath) {
        String path = "https://downloads.mysql.com/archives/get/p/3/file/mysql-connector-java-8.0.19.zip";
        return downMysqlDriver(path, savePath);
    }

    public static boolean downMysqlDriver(String urlStr, String savePath) {
        boolean driverPath = false;
        InputStream inputStream = null;
        ZipInputStream isZip = null;

        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置超时间为3秒
            conn.setConnectTimeout(5 * 1000);
            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");
            // conn.setRequestProperty("User-Agent", "Mozilla/4.76");
            // conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            // 得到输入流
            inputStream = conn.getInputStream();

            isZip = new ZipInputStream(inputStream, StandardCharsets.UTF_8);
            driverPath = downMysqlDriver(isZip, savePath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != isZip) {
                try {
                    isZip.close();
                } catch (IOException ignore) {
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignore) {
                }
            }
        }

        return driverPath;
    }

    private static boolean checkSavePath(String savePath) {
        String fileDir;
        String fileName;
        int pos = savePath.lastIndexOf("/");
        if (pos == -1) {
            pos = savePath.lastIndexOf("\\");
        }
        if (pos == -1) {
            return false;
        } else {
            fileDir = savePath.substring(0, pos);
            fileName = savePath.substring(pos + 1);

            new File(fileDir).mkdirs();

            return fileName.endsWith(".jar");
        }
    }

    private static boolean downMysqlDriver(ZipInputStream inputStream, String savePath) throws IOException {
        int pos;
        boolean done = false;
        String content;
        String name;
        String fileName;
        String driverPath = "";
        ZipEntry nextEntry = inputStream.getNextEntry();

        if (!checkSavePath(savePath)) {
            return false;
        }

        while (nextEntry != null) {
            name = nextEntry.getName();
            pos = name.lastIndexOf("/");
            fileName = name.substring(pos + 1);

            if (fileName.endsWith(".jar")) {
                driverPath = savePath;
                saveDriveFile(inputStream, driverPath);
                inputStream.closeEntry();
                done = true;
                break;
            }

            inputStream.closeEntry();
            nextEntry = inputStream.getNextEntry();
        }

        return done;
    }

    private static void saveDriveFile(InputStream inputStream, String filePath) {
        // 缓冲输出流，将内存中的数据，输出到对应的外部存储，比如u盘
        BufferedOutputStream bufferedOutputStream = null;
        // 目标文件，将下载的数据存入目标设备，以及文件名
        File destFile = new File(filePath);

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(destFile);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            byte[] buffer = new byte[4096];
            int len;

            destFile.createNewFile();

            //使用缓冲输出流，不停地写入字节
            int _byte;
            while ((_byte = inputStream.read(buffer)) != -1) {
                bufferedOutputStream.write(buffer, 0, _byte);
            }

            // 缓冲输出流刷新
            bufferedOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭相关的资源文件
            try {
                if (bufferedOutputStream != null) {
                    bufferedOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
